﻿using System.Data;

using MySql.Data.MySqlClient;

namespace EmbeddedSensorCloud.Plugin.MicroERP
{
    public abstract class MySQLDAOBase
    {
        #region Fields

        public readonly string ConnectionString;

        #endregion

        #region Constructor

        public MySQLDAOBase(string connectionString)
        {
            this.ConnectionString = connectionString;
        }

        #endregion

        protected MySqlConnection GetConnection()
        {
            try
            {
                MySqlConnection connection = new MySqlConnection(this.ConnectionString);
                connection.Open();
                return connection;
            }
            catch (MySqlException)
            {
                MySqlConnection.ClearAllPools();
                throw;
            }
        }

        /// <summary>
        /// Retrieves the last instered id from the database for the given connection.
        /// </summary>
        /// <exception cref="BadLastInsertIdException" />
        protected uint GetLastInsertId(MySqlConnection connection, MySqlTransaction transaction)
        {
            MySqlCommand lastIdCommand = new MySqlCommand("SELECT LAST_INSERT_ID();", connection, transaction);

            using (MySqlDataReader reader = lastIdCommand.ExecuteReader(CommandBehavior.SingleRow))
            {
                if (reader.Read())
                {
                    return reader.GetUInt32(0);
                }
                throw new BadLastInsertIdException();
            }
        }
    }
}
